﻿using ShiQuan.Logger;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace ShiQuan.Sockets
{
    /// <summary>
    /// Socket 客户端
    /// </summary>
    public class SocketClient : IDisposable
    {
        public string Server { get; set; }

        public int Port { get; set; }
        protected Socket _socket = null;
        /// <summary>
        /// 
        /// </summary>
        public Socket Socket
        {
            get { return this._socket; }
        }
        
        public SocketClient(string server, int port)
        {
            this.Server = server;
            this.Port = port;
        }
        /// <summary>
        /// 连接服务器
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public virtual bool Connect()
        {
            try
            {
                IPAddress ip = IPAddress.Parse(this.Server);
                IPEndPoint point = new IPEndPoint(ip, this.Port);

                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _socket.Connect(point);
                Console.WriteLine("服务器" + _socket.RemoteEndPoint.ToString() +"连接成功！");
                return true;
            }
            catch (Exception ex)
            {
                ThreadLogHelper.Error("连接服务器异常", ex);
                Console.WriteLine("连接服务器异常：" + ex.Message);
                return false;
            }
        }
        /// <summary>
        /// 发送信息
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public virtual bool Send(string msg,out string result)
        {
            result = string.Empty;
            try
            {
                if (this._socket == null)
                {
                    Console.WriteLine("");
                    return false;
                }
                byte[] buffer = Encoding.UTF8.GetBytes(msg);
                this._socket.Send(buffer);

                byte[] receive = new byte[1024 * 1024];
                int n = this._socket.Receive(receive);
                result = Encoding.UTF8.GetString(receive, 0, n);
                return true;
            }
            catch (Exception ex)
            {
                ThreadLogHelper.Error("客户端发送信息异常", ex);
                Console.WriteLine("客户端发送信息异常："+ex.Message);
                return false;
            }
        }
        public void Dispose()
        {
            this._socket.Disconnect(false);
            this._socket = null;
        }
    }
}
